﻿using System;
using System.Collections.Generic;

namespace Entities.Enumeration {

    public class WeightUnit {

        public readonly static WeightUnit KiloGram = new WeightUnit("KG",  "公斤", 1);
        public readonly static WeightUnit Gram     = new WeightUnit("G",   "克", 1000);
        public readonly static WeightUnit CGram    = new WeightUnit("J",   "斤", 0.5);

        private static readonly Dictionary<string,WeightUnit> Index = new Dictionary<string, WeightUnit> {
           {"KG", KiloGram},
           {"G",  Gram},
           {"J",  CGram}
        };

        public string Name  { get; private set; }
        public string CName { get; private set; }
        private readonly double _weight;

        public WeightUnit(string name, string cname, double weight) {
            Name    = name;
            CName   = cname;
            _weight = weight;
        }

        public double ConvertTo(double inputValue, WeightUnit outputUnit) {
            if (outputUnit == null) {
                return Math.Round(inputValue, 4);
            }
            return Math.Round(inputValue * (outputUnit._weight / _weight), 4);
        }

        public double ConvertFrom(double inputValue, WeightUnit inputUnit) {
            if (inputUnit == null) {
                return Math.Round(inputValue, 4);
            }
            return Math.Round(inputValue * (_weight / inputUnit._weight), 4);
        }

        public static WeightUnit GetInstance(string name) {
            return Index[name];
        }

        public static WeightUnit GetInstance(string name, WeightUnit def) {
            return Index[name] ?? def;
        }
    }
}